<?php
/**
 * CreateTime: 2023/2/1 10:26
 */

namespace App\Tools\USails;

use App\Func\AppFunc;
use App\Func\CurlFunc;

class USailsClient
{
    private $appId;
    private $appKey;
    private $url;
    private $requestType = "GET";
    private static $uSailsInstance;

    private function __construct()
    {
        $this->appId = AppFunc::getUSailsConfig()::USAILS_APP_ID;
        $this->appKey = AppFunc::getUSailsConfig()::USAILS_APP_KEY;
        $this->url = AppFunc::getUSailsConfig()::USAILS_URL;
    }

    private function __clone(): void{}

    public static function getInstance(){
        if(!self::$uSailsInstance){
            self::$uSailsInstance = new USailsClient();
        }
        return self::$uSailsInstance;
    }

    public function changeRequestType($type){
        $this->requestType = $type;
    }

    public function execute($path,$data){
        $time = time();
        $sign = hash("sha256", $this->appId.$this->appKey.$time);
        $publicHeader = [
            'appid:'.$this->appId,
            'timestamp:'.$time,
            'sign:'.$sign,
            'Content-type:application/json'
        ];
        $url = $this->url.$path;
        switch ($this->requestType){
            case "GET":
                return CurlFunc::CurlGet($url,1,$data,$publicHeader);
            case "POST":
            default:
                return CurlFunc::CurlPost($url,$data,$publicHeader);
        }
    }
}